package com.cskaoyan.market.admin.controller;

import com.cskaoyan.market.admin.service.MarketAdminAdminService;
import com.cskaoyan.market.admin.service.impl.MarketAdminAdminServiceImpl;
import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.db.domain.MarketAdminExample;
import com.cskaoyan.market.db.mapper.MarketAdminMapper;
import com.cskaoyan.market.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/admin/*")
public class AdminAdminController extends HttpServlet {
    private MarketAdminAdminService marketAdminAdminService = new MarketAdminAdminServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/admin/", "");
        switch (op) {
            case "list":
                list(req, resp);
                break;
            default:
                resp.setStatus(404);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/admin/", "");
        switch (op) {
            case "create":
                create(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
            case "delete":
                delete(req, resp);
                break;
            default:
                resp.setStatus(404);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String avatar = JacksonUtil.parseString(requestBody, "avatar");
        String id = JacksonUtil.parseString(requestBody, "id");
        Integer[] roleIds = new Integer[]{JacksonUtil.parseInteger(requestBody, "roleIds")};
        String username = JacksonUtil.parseString(requestBody, "username");
        marketAdminAdminService.delete(id);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String avatar = JacksonUtil.parseString(requestBody, "avatar");
        String id = JacksonUtil.parseString(requestBody, "id");
        List<Integer> roleIds = JacksonUtil.parseIntegerList(requestBody, "roleIds");
        String password = JacksonUtil.parseString(requestBody, "password");
        String username = JacksonUtil.parseString(requestBody, "username");
        SqlSession session = MyBatisUtil.getSession();
        MarketAdminMapper mapper = session.getMapper(MarketAdminMapper.class);
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        List<MarketAdmin> marketAdminList = mapper.selectByExample(marketAdminExample);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        if (username.length() < 6) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(601, "管理员名称不符合规定")));
            return;
        }
        if (password.length() < 6) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(602, "管理员密码长度不能小于6")));
        }
        MarketAdmin marketAdmin = marketAdminAdminService.update(avatar, roleIds.toArray(new Integer[0]), id, password, username);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketAdmin)));
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        SqlSession session = MyBatisUtil.getSession();
        MarketAdminMapper mapper = session.getMapper(MarketAdminMapper.class);
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        List<MarketAdmin> marketAdminList = mapper.selectByExample(marketAdminExample);
        String password = JacksonUtil.parseString(requestBody, "password");
        String username = JacksonUtil.parseString(requestBody, "username");
//        Integer[] roleIds = new Integer[]{JacksonUtil.parseInteger(requestBody, "roleIds")};
        List<Integer> roleIds = JacksonUtil.parseIntegerList(requestBody, "roleIds");
        if (username.length() < 6) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(601, "管理员名称不符合规定")));
            return;
        }
        for (MarketAdmin marketAdmin : marketAdminList) {
            if (marketAdmin.getUsername().equals(username)) {
                resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(601, "管理员名称不符合规定")));
                return;
            }
        }
        if (password.length() < 6) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(602, "管理员密码长度不能小于6")));
            return;
        }
        MarketAdmin marketAdmin = marketAdminAdminService.create(password, username, roleIds.toArray(new Integer[0]));
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketAdmin)));
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String username = req.getParameter("username");

        if (StringUtils.isEmpty(pageParam) || StringUtils.isEmpty(limitParam)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }
        int page = 0;
        int limit = 0;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        List<MarketAdmin> marketAdminList = marketAdminAdminService.getList(page, limit, sort, order, username);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(marketAdminList)));
    }
}
